#!/bin/bash
  
SVN_ROOT='https://supertain.googlecode.com/svn/trunk'

get_target_dir(){
  case $1 in
    prod) echo '/var/chroot/home/content/50/9624950/html/www.supertain.com';;
    demo) echo '/var/chroot/home/content/50/9624950/html/demo.supertain.com';;
    *) echo '';;
  esac
}

##############################################################################################

svn --help > /dev/null
if [ "$?" != 0 ]; then
  echo "Installing subversion..."
  cd ~
  wget http://www.erikfantasia.com/download/godaddy-svn-1.5.6.tar.gz
  tar zxvf godaddy-svn-1.5.6.tar.gz
  mv bashrc.svn .bashrc
  . ~/.bashrc
  rm godaddy-svn-1.5.6.tar.gz
fi

##############################################################################################
  
echo "Please enter environment: "
read env

auth=0
echo "Basic Auth (y/n): "
read basicauth
if [ "$basicauth" == "y" ]; then
  auth=1
fi

INSTALL_PATH=$(get_target_dir $env)

echo "Please enter the SVN revision (leave blank for HEAD): "
read rev
if [ "z$rev" == "z" ]; then
  rev="HEAD"
fi
  
echo "Exporting source from subversion..."
TEMP_DIR=/tmp/supertain.$rev
if [ -d "$TEMP_DIR" ]; then
  rm -rf $TEMP_DIR
fi 

svn export $SVN_ROOT $TEMP_DIR -r$rev

echo "Backing up existing files..."
if [ -d "$INSTALL_PATH/web" ]; then
  rm -rf $TEMP_DIR/web/uploads
  cp -r $INSTALL_PATH/web/uploads $TEMP_DIR/web/uploads
fi

echo "Setting up..."
rm -rf $INSTALL_PATH/*
mv $TEMP_DIR/* $INSTALL_PATH
cd $INSTALL_PATH
chmod -R 777 web/uploads log cache
mv web/frontend_$env.php web/index.php
mv web/backend_$env.php web/backend.php
rm -rf web/frontend_* web/backend_*
rm -rf install data

if [ "$auth" != "1" ]; then
  cp ~/basic_auth/_htaccess web/.htaccess
fi

/usr/local/php5/bin/php symfony cc > /dev/null
/usr/local/php5/bin/php symfony stn:create-admin --first-name=Admin --last-name=Admin --username=admin --password=admin --email=info@supertain.me --env=$env > /dev/null

echo ":: Setup is complete!"